package com.aidex.wxCompany;

import com.aidex.common.core.redis.RedisCache;
import com.aidex.common.utils.StringUtils;
import com.aidex.framework.cache.ConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Component
public class WxWrokMessageServiceImpl implements WxWrokMessageService {

    @Autowired
    private RedisCache redisCache;


    /**
     * @param phones  号码
     * @param content
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public Map<String, Object> sendTextMessageByUser(String[] phones, String content) {
        Map<String, Object> resultMap = new HashMap<>();
        String msg = "发送失败";
        String userId = null;
        String status = "500";
        List<String> userIdList = new ArrayList<>();
        for (String phone : phones) {
            Map<String, Object> result = this.getUserIdByPhone(phone);
            if (null != result) {
                if ((Boolean) result.get("isSuccess")) {
                    if (result.containsKey("userId") && StringUtils.isNotNull(result.get("userId"))) {
                        userIdList.add((String) result.get("userId"));
                    }
                }
            }
        }
        userId = String.join("|", userIdList.toArray(new String[0]));
        if (StringUtils.isNotNull(userId) && StringUtils.isNotEmpty(userId)) {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}";
            String agentId = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.agentId").getConfigValue();
            // 构造消息体
            Map<String, Object> message = new HashMap<>();
            message.put("touser", userId); // 接收用户ID（多个用|分隔）
            message.put("toparty", "");//部门ID
            message.put("totag", ""); //tag
            message.put("msgtype", "text");
            message.put("agentid", agentId);
            Map<String, String> text = new HashMap<>();
            text.put("content", content);
            message.put("text", text);
            // 发送POST请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Map> response = restTemplate.postForEntity(url, message, Map.class, getAccessToken());
            // 检查响应
            if (response.getStatusCode().is2xxSuccessful()) {
                Map<String, Object> body = response.getBody();
                if (body != null && 0 != (Integer) body.get("errcode")) {
                    msg = StringUtils.isNull(body.get("errmsg")) ? "参数获取失败" : body.get("errmsg").toString();
                } else {
                    msg = content;
                    status = "200";
                }
            } else {
                msg = "返回失败";
            }
        } else {
            msg = "userId为空";
        }
        resultMap.put("msg", msg);
        resultMap.put("phone", String.join(";", phones));
        resultMap.put("userId", userId);
        resultMap.put("status", status);
        return resultMap;
    }


    /**
     * @param wxUserIdList 企业微信用户ID集合
     * @param content
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public Map<String, Object> sendTextMessageByWxUserIds(String[] wxUserIdList, String content) {
        Map<String, Object> resultMap = new HashMap<>();
        String msg = "发送失败";
        String userId = null;
        String status = "500";

        userId = String.join("|", wxUserIdList);
        if (StringUtils.isNotEmpty(userId)) {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}";
            String agentId = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.agentId").getConfigValue();
            // 构造消息体
            Map<String, Object> message = new HashMap<>();
            message.put("touser", userId); // 接收用户ID（多个用|分隔）
            message.put("toparty", "");//部门ID
            message.put("totag", ""); //tag
            message.put("msgtype", "text");
            message.put("agentid", agentId);
            Map<String, String> text = new HashMap<>();
            text.put("content", content);
            message.put("text", text);
            // 发送POST请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Map> response = restTemplate.postForEntity(url, message, Map.class, getAccessToken());
            // 检查响应
            if (response.getStatusCode().is2xxSuccessful()) {
                Map<String, Object> body = response.getBody();
                if (body != null && 0 != (Integer) body.get("errcode")) {
                    msg = StringUtils.isNull(body.get("errmsg")) ? "参数获取失败" : body.get("errmsg").toString();
                } else {
                    msg = content;
                    status = "200";
                }
            } else {
                msg = "返回失败";
            }
        } else {
            msg = "userId为空";
        }
        resultMap.put("msg", msg);
        resultMap.put("userId", userId);
        resultMap.put("status", status);
        return resultMap;
    }

    @Override
    public Boolean sendTxtMessageFromRobotToGroup(String robot, String content, String[] mentionedList,
                                                  String[] mobileList) {
        Map<String, Object> message = new HashMap<>();
        message.put("msgtype", "text");
        Map<String, Object> contests = new HashMap<>();
        contests.put("content", content);
        if (mentionedList != null) {
            contests.put("mentioned_list", Arrays.asList(mentionedList)); // 确保这些是有效的用户ID
        }
        if (mobileList != null) {
            contests.put("mentioned_mobile_list", Arrays.asList(mobileList));
        }
        message.put("text", contests);
        // 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.postForEntity(robot, message, Map.class, getAccessToken());
        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null && 0 != (Integer) body.get("errcode")) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    @Override
    public String getAccessToken() {
        String corpId = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.corpId").getConfigValue();
        String corpSecret = ConfigUtils.getConfigByKeyNoCache("tencent.wxWork.corpSecret").getConfigValue();
        String accessToken = redisCache.getCacheObject("wxwork:accessToken");
        if (StringUtils.isEmpty(accessToken)) {
            String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpSecret}";
            Map<String, Object> response = new RestTemplate().getForObject(url, Map.class, corpId, corpSecret);
            accessToken = (String) response.get("access_token");
            Integer expiresTime = (Integer) response.get("expires_in");
            redisCache.setCacheObject("wxwork:accessToken", accessToken, expiresTime, TimeUnit.SECONDS);
        }
        return accessToken;
    }

    @Override
    public Map<String, Object> getUserIdByPhone(String phone) {
        Map<String, Object> result = new HashMap<>();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token={token}";
        // 构造消息体
        Map<String, Object> params = new HashMap<>();
        params.put("mobile", phone); // 接收用户ID（多个用|分隔）
        // 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.postForEntity(url, params, Map.class, getAccessToken());
        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null) {
                if (0 != (Integer) body.get("errcode")) {
                    result.put("isSuccess", false);
                    result.put("errmsg", (String) body.get("errmsg"));
                    result.put("userId", null);
                } else {
                    result.put("isSuccess", true);
                    result.put("errmsg", null);
                    result.put("userId", (String) body.get("userid"));
                }
            } else {
                result.put("isSuccess", false);
                result.put("errmsg", "返回参数错误");
                result.put("userId", null);
            }

        } else {
            result.put("isSuccess", false);
            result.put("errmsg", "响应错误");
            result.put("userId", null);
        }
        return result;
    }

    @Override
    public Boolean sendImageMessageFromRobotToGroup(String robot, String base64, String md5) {
        Map<String, Object> message = new HashMap<>();
        message.put("msgtype", "image");
        Map<String, Object> image = new HashMap<>();
        image.put("base64", base64);

        image.put("md5", md5);
        message.put("image", image);
        // 发送POST请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.postForEntity(robot, message, Map.class, getAccessToken());
        // 检查响应
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null && 0 != (Integer) body.get("errcode")) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}
